package com.sxm.yiwei.activitis;

import android.Manifest;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.support.v7.view.ContextThemeWrapper;
import android.text.Editable;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sxm.yiwei.MainActivity;
import com.sxm.yiwei.R;
import com.sxm.yiwei.adapters.HotSendLinkItemAdapter;
import com.sxm.yiwei.constant.Common;
import com.sxm.yiwei.constant.Constant;
import com.sxm.yiwei.tools.BaseIntents;
import com.sxm.yiwei.tools.CropPictures;
import com.sxm.yiwei.utils.InternetAddressUtis;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

public class FWHiteMeShopActivity extends BaseActivity implements View.OnClickListener{

    private ImageView fwhiteback;
    private EditText hiteEdit;
    private ImageView hiteimg1;
    private ImageView hiteimg2;
    private ImageView hiteimg3;
    private Button hitebt;
    private SharedPreferences sharedPreferences;
    private String token;
    private String userId;
    private String appId;
    private String shopid;

    private List<String> imglist = new ArrayList();
    private File mCurrentPhotoFile;
    private static final int PHOTO_TEXT = 3022;
    private static final int PHOTO_PICKED_WITH_DATA = 3021;
    /*用来标识请求照相功能的activity*/
    private static final int CAMERA_WITH_DATA = 3023;
    private static final File PHOTO_DIR = new File(Environment.getExternalStorageDirectory() + "/DCIM/Camera");
    private double currentIndex;
    private Bitmap photo;
    private String path1;
    private String from;
    private String id;
    private String type;
    private TextView hittitle;
    private BaseIntents baseIntents;
    private AlertDialog dialog;
    private ImageView backmain;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fwhite_me_shop);
        sharedPreferences = getSharedPreferences("userlogin", Context.MODE_PRIVATE);
        token = sharedPreferences.getString("token", "");
        userId = sharedPreferences.getString("userId", "");
        appId = sharedPreferences.getString("appid", "");
        Intent intent = getIntent();
        shopid = intent.getStringExtra("id");
        from = intent.getStringExtra("from");

        initHiteMeShopView();
        baseIntents = new BaseIntents();

        if (from.equals("abnormol")){
            hittitle.setText("申诉详情");
            hitebt.setText("取消申诉");
            getComplteMssage(shopid);
        }else if (from.equals("vendor")||from.equals(Constant.PASSENGER_APPEAL)){
            hitebt.setText("申诉");
            hittitle.setText("申诉中心");
        }else if (from.equals("shop")){
            hitebt.setText("确定");
            hittitle.setText("举报中心");
        }else {}
    }
        // 获取投诉信息
    private void getComplteMssage(String shopid) {
        RequestParams params = new RequestParams(InternetAddressUtis.Url+InternetAddressUtis.GETCOMPLITEMESSAGE);
        params.addHeader("Content-Type","application/json");
        params.addHeader("token",token);
        params.addHeader("appId",appId);
        params.addHeader("userId",userId);
        JSONObject object = new JSONObject();
        object.put("orderId",shopid);
        params.addParameter("params",object.toJSONString());
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.d("tag", "onSuccess: 申诉详情--"+result);
                JSONObject obj = JSON.parseObject(result);
                String status = obj.getString("status");
                if (status.equals("1")){
                    String data = obj.getString("data");
                    JSONObject obj1 = JSON.parseObject(data);
                    JSONArray complaintImage = obj1.getJSONArray("complaintImage");
                    String content = obj1.getString("content");
                    id = obj1.getString("id");

                    hiteEdit.setText(content);
                    if (complaintImage.size()==0){

                    }else {
                        switch (complaintImage.size()){
                            case 1:
                                x.image().bind(hiteimg1,InternetAddressUtis.IMG_URL+complaintImage.get(0));
                                break;
                            case 2:
                                x.image().bind(hiteimg1,InternetAddressUtis.IMG_URL+complaintImage.get(0));
                                x.image().bind(hiteimg2,InternetAddressUtis.IMG_URL+complaintImage.get(1));
                                break;
                            case 3:
                                x.image().bind(hiteimg1,InternetAddressUtis.IMG_URL+complaintImage.get(0));
                                x.image().bind(hiteimg2,InternetAddressUtis.IMG_URL+complaintImage.get(1));
                                x.image().bind(hiteimg3,InternetAddressUtis.IMG_URL+complaintImage.get(2));
                                break;
                        }
                    }
                }else {}




            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.d("tag", "onError: 申诉详情--"+ex);

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }
        // 取消投诉
    private void cancelComplite(String id) {
        RequestParams params = new RequestParams(InternetAddressUtis.Url+InternetAddressUtis.CANCELCOMPLTE);
        params.addHeader("Content-Type","application/json");
        params.addHeader("token",token);
        params.addHeader("appId",appId);
        params.addHeader("userId",userId);
        JSONObject object = new JSONObject();
        object.put("orderId",id);
        params.setBodyContent(object.toJSONString());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {

                JSONObject obj = JSON.parseObject(result);
                String status = obj.getString("status");
                if (status.equals("1")){
                    Toast.makeText(FWHiteMeShopActivity.this, "取消成功", Toast.LENGTH_SHORT).show();
                    finish();
                }else {}

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private void initHiteMeShopView() {
        fwhiteback = (ImageView) findViewById(R.id.fw_hitemeshop_back);
        hiteEdit = (EditText) findViewById(R.id.fw_hitemeshop_edit);
        hiteimg1 = (ImageView) findViewById(R.id.fw_hitemeshop_img1);
        hiteimg2 = (ImageView) findViewById(R.id.fw_hitemeshop_img2);
        hiteimg3 = (ImageView) findViewById(R.id.fw_hitemeshop_img3);
        hitebt = (Button) findViewById(R.id.fw_hitemeshop_hitebt);
        hittitle = (TextView) findViewById(R.id.hite_title);
        backmain = (ImageView) findViewById(R.id.fwhiteme_backmain);
        backmain.setOnClickListener(this);
        fwhiteback.setOnClickListener(this);
        hiteEdit.setOnClickListener(this);
        hiteimg1.setOnClickListener(this);
        hiteimg2.setOnClickListener(this);
        hiteimg3.setOnClickListener(this);
        hitebt.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.fwhiteme_backmain:

                startActivity(new Intent(FWHiteMeShopActivity.this, MainActivity.class));
                AppManager.getAppManager().finishAllActivity();
                break;
            case R.id.fw_hitemeshop_back:
                finish();
                break;
            case R.id.fw_hitemeshop_hitebt:

                if (from.equals("shop")){
                    String hitetext = String.valueOf(hiteEdit.getText());
                    if (hitetext.equals("")){
                        Toast.makeText(this, "请输入举报信息", Toast.LENGTH_SHORT).show();
                    }else if (imglist.size()>0){
                        AlertDialog.Builder builder = new AlertDialog.Builder(FWHiteMeShopActivity.this, R.style.NoBackGroundDialog);
                        View view = LayoutInflater.from(this).inflate(R.layout.progress_dialog, null);
                        builder.setView(view);
                        dialog = builder.create();
                        dialog.show();
                        reportShop();
                    }else {
                        Toast.makeText(FWHiteMeShopActivity.this, "举报图片不能少于一张", Toast.LENGTH_SHORT).show();

                    }


                }else if (from.equals("vendor")||from.equals(Constant.PASSENGER_APPEAL)){
                    String hitetext = String.valueOf(hiteEdit.getText());
                    if (hitetext.equals("")){
                        Toast.makeText(this, "请输入申诉信息", Toast.LENGTH_SHORT).show();
                    }else {
                        AlertDialog.Builder builder = new AlertDialog.Builder(FWHiteMeShopActivity.this, R.style.NoBackGroundDialog);
                        View view = LayoutInflater.from(this).inflate(R.layout.progress_dialog, null);
                        builder.setView(view);
                        dialog = builder.create();
                        dialog.show();
                        if (from.equals("vendor")){
                            reportService(InternetAddressUtis.Url+InternetAddressUtis.COMPLITESERVICE);
                        }else if (from.equals(Constant.PASSENGER_APPEAL)){
                            reportService(Common.HOST+Common.ORDER_APPEAL);
                        }
                    }

                }else if (from.equals("abnormol")){
                    final AlertDialog.Builder builder = new AlertDialog.Builder(FWHiteMeShopActivity.this);
                    builder.setMessage("你确定要取消投诉吗？");
                    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            builder.create().dismiss();
                        }
        }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            cancelComplite(shopid);
                        }
                    });
                    builder.create().show();

                }else {}

                break;
            case R.id.fw_hitemeshop_img1:

                currentIndex=1;
                doPickPhotoAction();
                break;
            case R.id.fw_hitemeshop_img2:

                currentIndex=2;
                doPickPhotoAction();
                break;
            case R.id.fw_hitemeshop_img3:

                currentIndex=3;
                doPickPhotoAction();
                break;
        }
    }
        // 服务申诉
    private void reportService(String url) {
        String message = String.valueOf(hiteEdit.getText());
        RequestParams params = new RequestParams(url);
        params.addHeader("Content-Type","multipart/form-data");
        params.addHeader("token",token);
        params.addHeader("appId",appId);
        params.addHeader("userId",userId);
        params.addBodyParameter("orderId",shopid);
        params.addBodyParameter("content",message);
        params.setMultipart(true);
            for (int i = 0; i < imglist.size(); i++) {
                params.addBodyParameter("complaint",new File(imglist.get(i)));
            }

        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                dialog.dismiss();
                Log.d("tag", "onSuccess: 申诉--"+result);
                JSONObject object = JSON.parseObject(result);
                String status = object.getString("status");
                if (status.equals("1")){
                    Toast.makeText(FWHiteMeShopActivity.this, "申诉成功", Toast.LENGTH_SHORT).show();
                    /*if (from.equals(Constant.PASSENGER_APPEAL)){
                        Intent intent = new Intent();

                    }*/
                    finish();
                }else {
                    String failure = object.getString("failure");
                    if (failure.equals("1049")){
                        Toast.makeText(FWHiteMeShopActivity.this, "您的申诉已提交，请勿重复提交", Toast.LENGTH_SHORT).show();
                    }
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                dialog.dismiss();
                Log.d("tag", "onError: 申诉--"+ex);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    // 举报店铺
    private void reportShop() {
        String message = String.valueOf(hiteEdit.getText());
        RequestParams params = new RequestParams(InternetAddressUtis.Url+InternetAddressUtis.SHOPREPORT);
        params.addHeader("Content-Type","multipart/form-data");
        params.addHeader("token",token);
        params.addHeader("appId",appId);
        params.addHeader("userId",userId);
        params.addBodyParameter("shopId",shopid);
        params.addBodyParameter("reason",message);
        params.setMultipart(true);
        for (int i = 0; i < imglist.size(); i++) {
            params.addBodyParameter("report",new File(imglist.get(i)));
        }
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.d("tag", "onSuccess:店铺举报--"+result);
                JSONObject object = JSON.parseObject(result);
                String status = object.getString("status");
                if (status.equals("1")){
                    dialog.dismiss();
                    Toast.makeText(FWHiteMeShopActivity.this, "举报成功", Toast.LENGTH_SHORT).show();
                    finish();
                }else if (status.equals("0")){
                    String failure = object.getString("failure");
                    if (failure.equals("1045")){
                        Toast.makeText(FWHiteMeShopActivity.this, "举报图片不能少于一张", Toast.LENGTH_SHORT).show();
                    }
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.d("tag", "onError: 你好---"+ex);
                dialog.dismiss();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }
    private void doPickPhotoAction() {
        final Context context = this;
        AlertDialog.Builder b1 = new AlertDialog.Builder(context);
        View view = LayoutInflater.from(context).inflate(R.layout.picture_dialog, null);
        b1.setView(view);

        TextView camere = (TextView) view.findViewById(R.id.picdia_camere);
        TextView pic = (TextView) view.findViewById(R.id.picdia_pic);
        TextView cancel1 = (TextView) view.findViewById(R.id.picdia_cancel);

        final AlertDialog dialog1 = b1.create();
        Window window = dialog1.getWindow();
        camere.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String status= Environment.getExternalStorageState();
                if(status.equals(Environment.MEDIA_MOUNTED)){//判断是否有SD卡
                    // index=0;
                    baseIntents.doTakePhoto();// 用户点击了从照相机获取
                    dialog1.dismiss();
                }
                else{
                    Toast.makeText(context, "没有SD卡", Toast.LENGTH_SHORT).show();
                }
            }
        });
        pic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                baseIntents.doPickPhotoFromGallery();// 从相册中去获取
                dialog1.dismiss();
            }
        });
        cancel1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog1.dismiss();
            }
        });
        dialog1.show();
        window.setGravity(Gravity.BOTTOM);
    }


    // 因为调用了Camera和Gally所以要判断他们各自的返回情况,他们启动时是这样的startActivityForResult
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK)
            return;
        switch (requestCode) {
            case PHOTO_PICKED_WITH_DATA: {// 调用Gallery返回的
                //final Bitmap photo = data.getParcelableExtra("data");
                Bitmap photo = data.getParcelableExtra("data");
                //  sengimg.setImageBitmap(photo);
                String s = CropPictures.saveBitmapFile(photo, baseIntents.getPhotoFileName());
                imglist.add(s);
                if (currentIndex ==1){
                    hiteimg1.setImageBitmap(photo);
                }else if (currentIndex ==2){
                    hiteimg2.setImageBitmap(photo);
                }else if (currentIndex ==3){
                    hiteimg3.setImageBitmap(photo);
                }
                break;
            }
            case CAMERA_WITH_DATA: {// 照相机程序返回的,再次调用图片剪辑程序去修剪图片
                baseIntents.doCropPhoto(baseIntents.mCurrentPhotoFile);

                break;
            }
            case PHOTO_TEXT:
                Uri data1 = data.getData();
                if (!TextUtils.isEmpty(data1.getAuthority())){
                    ContentResolver resolver = getContentResolver();
                    try {
                        photo = MediaStore.Images.Media.getBitmap(resolver, data1);
                        String[] proj = {MediaStore.Images.Media.DATA};
                        Cursor cursor = managedQuery(data1, proj, null, null, null);
                        if (cursor==null){
                            Toast.makeText(this, "没有找到图片", Toast.LENGTH_SHORT).show();
                        }else {
                            cursor.moveToFirst();
                            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                            //图片路径
                            path1 = cursor.getString(column_index);

                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }else {
                    path1 = data1.getPath();
                }
                File file = new File(path1);
                baseIntents.doCropPhoto(file);
                break;

        }
    }

}
